package com.toro.server.handler;


import com.toro.message.GroupChatResponseMessage;
import com.toro.message.GroupCreateRequestMessage;
import com.toro.message.GroupCreateResponseMessage;
import com.toro.domain.Group;
import com.toro.dao.GroupSession;
import com.toro.dao.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: GroupCreateRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:47
 */
@ChannelHandler.Sharable
@Slf4j
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        log.info("创建群请求：{}", groupCreateRequestMessage);
        String groupName = groupCreateRequestMessage.getGroupName();
        ArrayList<String> members = groupCreateRequestMessage.getMembers();
        String creator = groupCreateRequestMessage.getCreator();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        boolean emptyGroup = groupSession.EmptyGroup(groupName);

        if (!emptyGroup) {
            groupSession.createGroup(groupName, members, creator);
            //发送创建成功
            channelHandlerContext.writeAndFlush(new GroupChatResponseMessage(true, "群 " + groupName + "创建成功"));
            //成员被发送拉群消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
//            log.debug("成员Channel {}",membersChannel);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入 " + creator + " 创建的群 " + groupName));
            }
        } else {
            channelHandlerContext.writeAndFlush(new GroupChatResponseMessage(false, groupName + "已经存在"));
        }
    }
}
